<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class rate_model extends MY_Model {
	
	protected $table_company = "rate_company";
	protected $table_contact = "rate_contact";
	
	/**** Company Rate ****/
	function company($data)
	{
		// STEP 1 Delete old record if exist
		
		$this->db->where('user_id',$data['user_id']);
		$this->db->where('company_id',$data['company_id']);
		$count = $this->db->get($this->table_company);

		if($count->num_rows > 0)
		{
			//Update
			$this->db->where('user_id',$data['user_id']);
			$this->db->where('company_id',$data['company_id']);
			return $this->db->update($this->table_company, $data);
		}
		elseif($count->num_rows == 0){
			//Insert
			return $this->db->insert($this->table_company, $data); 
		}
	}
	
	function avg_company($id)
	{
		$this->db->select_avg('rate');
		$this->db->where('company_id',$id);
		$query = $this->db->get($this->table_company);
		
		if ($query->num_rows())
		{
			return $query->row();
		}
		
		return false;
	}
	
	function count_rates_per_company($id)
	{
		
		$this->db->where('company_id',$id);
		$this->db->from($this->table_company);
		$query = $this->db->count_all_results();
		
		if ($query)
		{
			return $query;
		}
		
		return false;
	}
	
	/**** Contact Rate ****/
	function contact($data)
	{
		// STEP 1 Delete old record if exist
		
		$this->db->where('user_id',$data['user_id']);
		$this->db->where('contact_id',$data['contact_id']);
		$count = $this->db->get($this->table_contact);

		if($count->num_rows > 0)
		{
			//Update
			$this->db->where('user_id',$data['user_id']);
			$this->db->where('contact_id',$data['contact_id']);
			return $this->db->update($this->table_contact, $data);
		}
		elseif($count->num_rows == 0){
			//Insert
			return $this->db->insert($this->table_contact, $data); 
		}
	}
	
	function avg_contact($id)
	{
		$this->db->select_avg('rate');
		$this->db->where('contact_id',$id);
		$query = $this->db->get($this->table_contact);
		
		if ($query->num_rows())
		{
			return $query->row();
		}
		
		return false;
	}
	
	function count_rates_per_contact($id)
	{
		
		$this->db->where('contact_id',$id);
		$this->db->from($this->table_contact);
		$query = $this->db->count_all_results();
		
		if ($query)
		{
			return $query;
		}
		
		return false;
	}

}
